package pinboard.dataLayer.net;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import pinboard.dataLayer.potocol.op.FixedSizeLoader;

public class RenderClientPipe extends BaseClientPipe {

    protected FixedSizeLoader msgLoader = new FixedSizeLoader();

    public RenderClientPipe(NetAddressInfo address, ClientPipeListener listener) {
        super(address, listener);
    }

    public RenderClientPipe(NetAddressInfo address) {
        super(address);
    }

    @Override
    protected void initHandler(IoConnector connector) {
        connector.setHandler(new IoHandlerAdapter() {
            @Override
            public void messageReceived(IoSession ioSession, Object o) throws Exception {
                boolean canDo = false;
                synchronized (netStateLock) {
                    if (RenderClientPipe.this.innerSession == ioSession) {
                        canDo = true;
                    }
                    if (canDo) {
                        IoBuffer ioBuffer = (IoBuffer) o;
                        byte[] msgBytes = new byte[ioBuffer.limit()];
                        ioBuffer.get(msgBytes);
                        byte[][] fullBags = msgLoader.fill(msgBytes);

                        if (fullBags != null && fullBags.length > 0 && RenderClientPipe.this.clientPipeListener != null) {
                            for (int i = 0; i < fullBags.length; i++) {
                                RenderClientPipe.this.clientPipeListener.onMessage(RenderClientPipe.this, fullBags[i]);
                            }
                        }
                    }
                }
            }
        });
    }
}
